<template>
  <div class="referral-withdraw-page">
    <div class="page-header">
      <h1>추천인 수익 출금 관리</h1>
    </div>

    <!-- 筛选器 -->
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="상태">
          <el-select v-model="filterForm.status" placeholder="전체" style="width: 150px">
            <el-option label="전체" value="all" />
            <el-option label="대기 중" value="PENDING" />
            <el-option label="승인됨" value="CONFIRMED" />
            <el-option label="거부됨" value="FAILED" />
            <el-option label="취소됨" value="CANCELLED" />
          </el-select>
        </el-form-item>

        <el-form-item label="사용자 ID">
          <el-input v-model="filterForm.userId" placeholder="사용자 ID" style="width: 150px" clearable />
        </el-form-item>

        <el-form-item label="시작 날짜">
          <el-date-picker
            v-model="filterForm.startDate"
            type="date"
            placeholder="시작 날짜"
            style="width: 180px"
          />
        </el-form-item>

        <el-form-item label="종료 날짜">
          <el-date-picker
            v-model="filterForm.endDate"
            type="date"
            placeholder="종료 날짜"
            style="width: 180px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadWithdrawals">검색</el-button>
          <el-button @click="resetFilters">초기화</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <el-card class="stat-card pending">
        <div class="stat-label">대기 중</div>
        <div class="stat-value">{{ summary.pending.count }}</div>
        <div class="stat-amount">{{ formatCurrency(summary.pending.amount) }}원</div>
      </el-card>
      <el-card class="stat-card confirmed">
        <div class="stat-label">승인됨</div>
        <div class="stat-value">{{ summary.confirmed.count }}</div>
        <div class="stat-amount">{{ formatCurrency(summary.confirmed.amount) }}원</div>
      </el-card>
      <el-card class="stat-card failed">
        <div class="stat-label">거부됨</div>
        <div class="stat-value">{{ summary.failed.count }}</div>
        <div class="stat-amount">{{ formatCurrency(summary.failed.amount) }}원</div>
      </el-card>
      <el-card class="stat-card cancelled">
        <div class="stat-label">취소됨</div>
        <div class="stat-value">{{ summary.cancelled.count }}</div>
        <div class="stat-amount">{{ formatCurrency(summary.cancelled.amount) }}원</div>
      </el-card>
    </div>

    <!-- 提现列表 -->
    <el-card shadow="never">
      <template #header>
        <div class="table-header">
          <span>추천인 수익 출금 목록</span>
          <el-button
            type="primary"
            size="small"
            :loading="isExporting"
            @click="handleExportExcel"
          >
            Excel 내보내기
          </el-button>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="withdrawals"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="사용자" width="150">
          <template #default="{ row }">
            <div>{{ row.user.name }}</div>
            <div class="user-id">ID: {{ row.user.id }}</div>
          </template>
        </el-table-column>
        <el-table-column label="추천 코드" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ row.user.referralCode }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="출금 금액" width="150">
          <template #default="{ row }">
            <div class="amount-cell">
              <div class="krw-amount">{{ formatCurrency(row.amountKrw) }}원</div>
              <div class="near-amount">{{ formatNear(row.amountNear) }} NEAR</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="NEAR 가격" width="120">
          <template #default="{ row }">
            {{ formatCurrency(row.nearPrice) }}원
          </template>
        </el-table-column>
        <el-table-column label="은행 정보" width="200">
          <template #default="{ row }">
            <div>{{ row.bankName }}</div>
            <div class="account-info">{{ row.accountHolder }}</div>
            <div class="account-number">{{ row.bankAccount }}</div>
          </template>
        </el-table-column>
        <el-table-column label="상태" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="신청 날짜" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="작업" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'PENDING'"
              type="success"
              size="small"
              @click="handleApprove(row)"
            >
              승인
            </el-button>
            <el-button
              v-if="row.status === 'PENDING'"
              type="danger"
              size="small"
              @click="handleReject(row)"
            >
              거부
            </el-button>
            <el-button
              v-if="row.status !== 'PENDING'"
              type="info"
              size="small"
              @click="viewDetail(row)"
            >
              상세
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approveDialogVisible"
      title="출금 승인"
      width="500px"
    >
      <el-form :model="approveForm" label-width="120px">
        <el-form-item label="사용자">
          <span>{{ currentWithdrawal?.user.name }}</span>
        </el-form-item>
        <el-form-item label="출금 금액">
          <span>{{ formatCurrency(currentWithdrawal?.amountKrw || 0) }}원</span>
        </el-form-item>
        <el-form-item label="은행 계좌">
          <div>
            <div>{{ currentWithdrawal?.bankName }}</div>
            <div>{{ currentWithdrawal?.bankAccount }}</div>
            <div>{{ currentWithdrawal?.accountHolder }}</div>
          </div>
        </el-form-item>
        <el-form-item label="관리자 메모">
          <el-input
            v-model="approveForm.note"
            type="textarea"
            :rows="3"
            placeholder="메모를 입력하세요 (선택 사항)"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approveDialogVisible = false">취소</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="confirmApprove"
        >
          승인 확인
        </el-button>
      </template>
    </el-dialog>

    <!-- 拒绝对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="출금 거부"
      width="500px"
    >
      <el-form :model="rejectForm" label-width="120px">
        <el-form-item label="사용자">
          <span>{{ currentWithdrawal?.user.name }}</span>
        </el-form-item>
        <el-form-item label="출금 금액">
          <span>{{ formatCurrency(currentWithdrawal?.amountKrw || 0) }}원</span>
        </el-form-item>
        <el-form-item label="거부 사유" required>
          <el-input
            v-model="rejectForm.note"
            type="textarea"
            :rows="3"
            placeholder="거부 사유를 입력하세요"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectDialogVisible = false">취소</el-button>
        <el-button
          type="danger"
          :loading="submitting"
          @click="confirmReject"
        >
          거부 확인
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="출금 상세 정보"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="사용자 이름">
          {{ currentWithdrawal?.user.name }}
        </el-descriptions-item>
        <el-descriptions-item label="사용자 ID">
          {{ currentWithdrawal?.user.id }}
        </el-descriptions-item>
        <el-descriptions-item label="추천 코드">
          {{ currentWithdrawal?.user.referralCode }}
        </el-descriptions-item>
        <el-descriptions-item label="출금 금액 (KRW)">
          {{ formatCurrency(currentWithdrawal?.amountKrw || 0) }}원
        </el-descriptions-item>
        <el-descriptions-item label="출금 금액 (NEAR)">
          {{ formatNear(currentWithdrawal?.amountNear || 0) }} NEAR
        </el-descriptions-item>
        <el-descriptions-item label="NEAR 가격">
          {{ formatCurrency(currentWithdrawal?.nearPrice || 0) }}원
        </el-descriptions-item>
        <el-descriptions-item label="은행명">
          {{ currentWithdrawal?.bankName }}
        </el-descriptions-item>
        <el-descriptions-item label="계좌 번호">
          {{ currentWithdrawal?.bankAccount }}
        </el-descriptions-item>
        <el-descriptions-item label="예금주">
          {{ currentWithdrawal?.accountHolder }}
        </el-descriptions-item>
        <el-descriptions-item label="상태">
          <el-tag :type="getStatusType(currentWithdrawal?.status)">
            {{ getStatusText(currentWithdrawal?.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="신청 날짜" :span="2">
          {{ formatDateTime(currentWithdrawal?.createdAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="처리 날짜" :span="2">
          {{ currentWithdrawal?.processedAt ? formatDateTime(currentWithdrawal.processedAt) : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="관리자 메모" :span="2">
          {{ currentWithdrawal?.adminNote || '-' }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">닫기</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminApi } from '@/api/referral'
import { exportToExcel, formatAmount as formatAmountForExcel, formatNearAmount as formatNearForExcel, formatDateTimeString } from '@/utils/exportExcel'
import type { ExportHeader } from '@/utils/exportExcel'

// 响应式数据
const loading = ref(false)
const isExporting = ref(false)
const withdrawals = ref<any[]>([])
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0,
  totalPages: 0
})

const summary = reactive({
  pending: { count: 0, amount: 0 },
  confirmed: { count: 0, amount: 0 },
  failed: { count: 0, amount: 0 },
  cancelled: { count: 0, amount: 0 }
})

const filterForm = reactive({
  status: 'all',
  userId: '',
  startDate: null as Date | null,
  endDate: null as Date | null
})

// 对话框相关
const approveDialogVisible = ref(false)
const rejectDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const submitting = ref(false)
const currentWithdrawal = ref<any>(null)

const approveForm = reactive({
  note: ''
})

const rejectForm = reactive({
  note: ''
})

// 初始化
onMounted(() => {
  loadWithdrawals()
})

// 加载提现列表
const loadWithdrawals = async () => {
  try {
    loading.value = true
    const params: any = {
      page: pagination.page,
      limit: pagination.limit
    }

    if (filterForm.status !== 'all') {
      params.status = filterForm.status
    }
    if (filterForm.userId) {
      params.userId = filterForm.userId
    }
    if (filterForm.startDate) {
      params.startDate = filterForm.startDate
    }
    if (filterForm.endDate) {
      params.endDate = filterForm.endDate
    }

    const data = await adminApi.getReferralWithdrawList(params)
    withdrawals.value = data.records
    Object.assign(summary, data.summary)
    Object.assign(pagination, data.pagination)
  } catch (error: any) {
    console.error('출금 목록 로드 실패:', error)
    ElMessage.error(error.message || '목록 조회에 실패했습니다')
  } finally {
    loading.value = false
  }
}

// 重置筛选器
const resetFilters = () => {
  filterForm.status = 'all'
  filterForm.userId = ''
  filterForm.startDate = null
  filterForm.endDate = null
  pagination.page = 1
  loadWithdrawals()
}

// Excel 내보내기
const handleExportExcel = async () => {
  try {
    isExporting.value = true

    // 构建导出参数（与当前筛选条件一致）
    const params: any = {
      exportAll: 'true' // 导出全部数据
    }

    if (filterForm.status !== 'all') {
      params.status = filterForm.status
    }
    if (filterForm.userId) {
      params.userId = filterForm.userId
    }
    if (filterForm.startDate) {
      params.startDate = filterForm.startDate
    }
    if (filterForm.endDate) {
      params.endDate = filterForm.endDate
    }

    // 调用API获取全部数据
    const response = await adminApi.getReferralWithdrawList(params)

    if (!response.records || response.records.length === 0) {
      ElMessage.warning('내보낼 데이터가 없습니다')
      return
    }

    const records = response.records

    // 定义导出的列
    const headers: ExportHeader[] = [
      { label: 'ID', prop: 'id' },
      { label: '사용자', prop: 'user.name' },
      { label: '사용자 ID', prop: 'user.id' },
      { label: '추천 코드', prop: 'user.referralCode' },
      {
        label: '출금 금액 (₩)',
        prop: 'amountKrw',
        formatter: (val) => formatAmountForExcel(val)
      },
      {
        label: '출금 금액 (NEAR)',
        prop: 'amountNear',
        formatter: (val) => formatNearForExcel(val)
      },
      {
        label: '상태',
        prop: 'status',
        formatter: (val) => getStatusText(val)
      },
      {
        label: '신청 시간',
        prop: 'createdAt',
        formatter: (val) => formatDateTimeString(val)
      },
      {
        label: '처리 시간',
        prop: 'processedAt',
        formatter: (val) => val ? formatDateTimeString(val) : '-'
      }
    ]

    // 导出Excel
    exportToExcel({
      fileName: '추천인수익출금관리',
      headers,
      data: records,
      sheetName: '추천인 수익 출금 목록'
    })

    ElMessage.success(`${records.length}건의 데이터를 성공적으로 내보냈습니다`)
  } catch (error: any) {
    console.error('Excel 내보내기 실패:', error)
    ElMessage.error(error.message || 'Excel 내보내기에 실패했습니다')
  } finally {
    isExporting.value = false
  }
}

// 处理分页
const handlePageChange = (page: number) => {
  pagination.page = page
  loadWithdrawals()
}

const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  loadWithdrawals()
}

// 审批操作
const handleApprove = (row: any) => {
  currentWithdrawal.value = row
  approveForm.note = ''
  approveDialogVisible.value = true
}

const confirmApprove = async () => {
  try {
    submitting.value = true
    await adminApi.processReferralWithdraw(currentWithdrawal.value.id, {
      action: 'approve',
      note: approveForm.note
    })
    ElMessage.success('출금이 승인되었습니다')
    approveDialogVisible.value = false
    await loadWithdrawals()
  } catch (error: any) {
    console.error('승인 실패:', error)
    ElMessage.error(error.message || '승인에 실패했습니다')
  } finally {
    submitting.value = false
  }
}

// 拒绝操作
const handleReject = (row: any) => {
  currentWithdrawal.value = row
  rejectForm.note = ''
  rejectDialogVisible.value = true
}

const confirmReject = async () => {
  if (!rejectForm.note.trim()) {
    ElMessage.warning('거부 사유를 입력해 주세요')
    return
  }

  try {
    submitting.value = true
    await adminApi.processReferralWithdraw(currentWithdrawal.value.id, {
      action: 'reject',
      note: rejectForm.note
    })
    ElMessage.success('출금이 거부되었습니다')
    rejectDialogVisible.value = false
    await loadWithdrawals()
  } catch (error: any) {
    console.error('거부 실패:', error)
    ElMessage.error(error.message || '거부에 실패했습니다')
  } finally {
    submitting.value = false
  }
}

// 查看详情
const viewDetail = (row: any) => {
  currentWithdrawal.value = row
  detailDialogVisible.value = true
}

// 工具函数
const formatCurrency = (value: number): string => {
  return Math.floor(value).toLocaleString('ko-KR')
}

const formatNear = (value: number): string => {
  return Number(value).toLocaleString('en-US', {
    minimumFractionDigits: 4,
    maximumFractionDigits: 4
  })
}

const formatDateTime = (date: string | undefined): string => {
  if (!date) return '-'
  return new Date(date).toLocaleString('ko-KR')
}

const getStatusType = (status: string | undefined): string => {
  const statusMap: Record<string, string> = {
    PENDING: 'warning',
    CONFIRMED: 'success',
    FAILED: 'danger',
    CANCELLED: 'info'
  }
  return statusMap[status || ''] || 'info'
}

const getStatusText = (status: string | undefined): string => {
  const statusMap: Record<string, string> = {
    PENDING: '대기 중',
    CONFIRMED: '승인됨',
    FAILED: '거부됨',
    CANCELLED: '취소됨'
  }
  return statusMap[status || ''] || '-'
}
</script>

<style scoped lang="scss">
.referral-withdraw-page {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;

  h1 {
    font-size: 1.5rem;
    font-weight: 600;
    color: #1a202c;
    margin: 0;
  }
}

.filter-card {
  margin-bottom: 24px;

  .filter-form {
    margin-bottom: 0;
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 24px;

  .stat-card {
    text-align: center;
    padding: 20px;

    .stat-label {
      font-size: 0.875rem;
      color: #64748b;
      margin-bottom: 8px;
    }

    .stat-value {
      font-size: 2rem;
      font-weight: 700;
      margin-bottom: 4px;
    }

    .stat-amount {
      font-size: 0.875rem;
      color: #64748b;
    }

    &.pending {
      .stat-value {
        color: #f59e0b;
      }
    }

    &.confirmed {
      .stat-value {
        color: #10b981;
      }
    }

    &.failed {
      .stat-value {
        color: #ef4444;
      }
    }

    &.cancelled {
      .stat-value {
        color: #6b7280;
      }
    }
  }
}

.user-id {
  font-size: 0.75rem;
  color: #94a3b8;
}

.amount-cell {
  .krw-amount {
    font-weight: 600;
    color: #1a202c;
  }

  .near-amount {
    font-size: 0.75rem;
    color: #64748b;
  }
}

.account-info {
  font-size: 0.75rem;
  color: #64748b;
}

.account-number {
  font-size: 0.75rem;
  color: #94a3b8;
  font-family: monospace;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
  color: #333;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

@media (max-width: 1024px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 640px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>
